import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @Author Sivir.Tian
 * @Date 2024-05-15-10:54
 * @Description PACKAGE_NAME
 * @Version 1.0.0
 */
@WebServlet(name = "aa", value = "/download")
public class DownLoadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name=request.getParameter("fileName");
        String url="/"+name;
//将响应的内容设置为通用的二进制流
        response.setContentType("application/octet-stream");
//attachment 告诉浏览器以附件的方式下载文件(弹出下载框)
        name=URLEncoder.encode(name,"utf-8");
        response.addHeader("Content-Disposition","attachment;fileName="+name);
        request.getRequestDispatcher(url).forward(request, response);
//清空缓冲区:将服务端缓冲区的文件内容,立即权并不传送给客户端
        response.flushBuffer();
    }
}

